import { NextRequest, NextResponse } from 'next/server';
import { IndependentTablesDatabase } from '../../../lib/independent-tables-database';
import { verifyDeletePermission } from '@/lib/auth-middleware';

// 创建数据库实例
let db: IndependentTablesDatabase;

function getDatabase() {
  if (!db) {
    db = new IndependentTablesDatabase();
  }
  return db;
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const deviceId = searchParams.get('deviceId');

    const database = getDatabase();

    if (deviceId) {
      // 获取特定设备
      const deviceIdNum = parseInt(deviceId);
      if (isNaN(deviceIdNum)) {
        return NextResponse.json({ error: '设备ID必须是数字' }, { status: 400 });
      }

      const device = database.getDeviceById(deviceIdNum);
      if (!device) {
        return NextResponse.json({ error: '设备不存在' }, { status: 404 });
      }

      // 获取设备的所有参数
      const parameters = {
        naming: database.getDeviceNamingParameters(deviceIdNum),
        position: database.getDevicePositionParameters(deviceIdNum),
        base: database.getDeviceBaseParameters(deviceIdNum)
      };

      return NextResponse.json({
        success: true,
        device: device,
        parameters: parameters,
        tableNames: database.getDeviceTableNames(deviceIdNum)
      });
    } else {
      // 获取所有设备
      const devices = database.getAllDevices();
      
      return NextResponse.json({
        success: true,
        devices: devices,
        count: devices.length
      });
    }

  } catch (error) {
    console.error('获取设备失败:', error);
    return NextResponse.json(
      { error: '获取设备失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { device_id, name, classification_name, classification_code, specialty, naming_table_id, position_table_id, base_params_table_id, tech_spec_table_id, sequence_number, remarks } = body;

    if (!device_id || !name || !classification_name || !classification_code || !specialty) {
      return NextResponse.json({ error: '缺少必要的设备信息' }, { status: 400 });
    }

    const deviceIdNum = parseInt(device_id);
    if (isNaN(deviceIdNum)) {
      return NextResponse.json({ error: '设备ID必须是数字' }, { status: 400 });
    }

    const database = getDatabase();

    // 检查设备是否已存在
    const existingDevice = database.getDeviceById(deviceIdNum);
    if (existingDevice) {
      return NextResponse.json({ error: '设备ID已存在' }, { status: 409 });
    }

    // 创建新设备（会自动创建独立的属性表）
    const newDevice = database.insertDevice({
      device_id: deviceIdNum,
      name,
      classification_name,
      classification_code,
      specialty,
      naming_table_id: naming_table_id || '',
      position_table_id: position_table_id || '',
      base_params_table_id: base_params_table_id || '',
      tech_spec_table_id: tech_spec_table_id || '',
      sequence_number: sequence_number || '',
      remarks: remarks || ''
    });

    return NextResponse.json({
      success: true,
      message: '设备创建成功',
      device: newDevice,
      tableNames: database.getDeviceTableNames(deviceIdNum)
    });

  } catch (error) {
    console.error('创建设备失败:', error);
    return NextResponse.json(
      { error: '创建设备失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { device_id, name, classification_name, classification_code, specialty, naming_table_id, position_table_id, base_params_table_id, tech_spec_table_id, sequence_number, remarks } = body;

    if (!device_id) {
      return NextResponse.json({ error: '缺少设备ID' }, { status: 400 });
    }

    const deviceIdNum = parseInt(device_id);
    if (isNaN(deviceIdNum)) {
      return NextResponse.json({ error: '设备ID必须是数字' }, { status: 400 });
    }

    const database = getDatabase();

    // 检查设备是否存在
    const existingDevice = database.getDeviceById(deviceIdNum);
    if (!existingDevice) {
      return NextResponse.json({ error: '设备不存在' }, { status: 404 });
    }

    // 构建更新SQL
    const updateFields = [];
    const updateValues = [];
    
    if (name !== undefined) {
      updateFields.push('name = ?');
      updateValues.push(name);
    }
    if (classification_name !== undefined) {
      updateFields.push('classification_name = ?');
      updateValues.push(classification_name);
    }
    if (classification_code !== undefined) {
      updateFields.push('classification_code = ?');
      updateValues.push(classification_code);
    }
    if (specialty !== undefined) {
      updateFields.push('specialty = ?');
      updateValues.push(specialty);
    }
    if (naming_table_id !== undefined) {
      updateFields.push('naming_table_id = ?');
      updateValues.push(naming_table_id);
    }
    if (position_table_id !== undefined) {
      updateFields.push('position_table_id = ?');
      updateValues.push(position_table_id);
    }
    if (base_params_table_id !== undefined) {
      updateFields.push('base_params_table_id = ?');
      updateValues.push(base_params_table_id);
    }
    if (tech_spec_table_id !== undefined) {
      updateFields.push('tech_spec_table_id = ?');
      updateValues.push(tech_spec_table_id);
    }
    if (sequence_number !== undefined) {
      updateFields.push('sequence_number = ?');
      updateValues.push(sequence_number);
    }
    if (remarks !== undefined) {
      updateFields.push('remarks = ?');
      updateValues.push(remarks);
    }
    
    updateFields.push('updated_at = ?');
    updateValues.push(new Date().toISOString());
    updateValues.push(deviceIdNum);

    // 执行更新
    const updateSql = `UPDATE devices SET ${updateFields.join(', ')} WHERE device_id = ?`;
    const stmt = (database as any).db.prepare(updateSql);
    const result = stmt.run(...updateValues);

    if (result.changes === 0) {
      return NextResponse.json({ error: '设备更新失败' }, { status: 500 });
    }

    // 获取更新后的设备信息
    const updatedDevice = database.getDeviceById(deviceIdNum);

    return NextResponse.json({
      success: true,
      message: '设备更新成功',
      device: updatedDevice,
      changes: result.changes
    });

  } catch (error) {
    console.error('更新设备失败:', error);
    return NextResponse.json(
      { error: '更新设备失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    // Verify authentication and delete permissions
    const authResult = await verifyDeletePermission();
    if (!authResult.success) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }

    if (!authResult.canDelete) {
      return NextResponse.json({
        success: false,
        error: '权限不足：无法删除设备'
      }, { status: 403 });
    }

    const { searchParams } = new URL(request.url);
    const deviceId = searchParams.get('deviceId');

    if (!deviceId) {
      return NextResponse.json({ error: '缺少设备ID参数' }, { status: 400 });
    }

    const deviceIdNum = parseInt(deviceId);
    if (isNaN(deviceIdNum)) {
      return NextResponse.json({ error: '设备ID必须是数字' }, { status: 400 });
    }

    const database = getDatabase();

    // 检查设备是否存在
    const existingDevice = database.getDeviceById(deviceIdNum);
    if (!existingDevice) {
      return NextResponse.json({ error: '设备不存在' }, { status: 404 });
    }

    // 获取表名
    const tableNames = database.getDeviceTableNames(deviceIdNum);

    // 删除设备的独立属性表
    const dropTables = [
      `DROP TABLE IF EXISTS ${tableNames.naming}`,
      `DROP TABLE IF EXISTS ${tableNames.position}`,
      `DROP TABLE IF EXISTS ${tableNames.base}`
    ];

    for (const dropSql of dropTables) {
      (database as any).db.exec(dropSql);
    }

    // 删除设备记录
    const deleteSql = 'DELETE FROM devices WHERE device_id = ?';
    const stmt = (database as any).db.prepare(deleteSql);
    const result = stmt.run(deviceIdNum);

    if (result.changes === 0) {
      return NextResponse.json({ error: '设备删除失败' }, { status: 500 });
    }

    return NextResponse.json({
      success: true,
      message: '设备及其相关数据删除成功',
      deletedDevice: existingDevice,
      deletedTables: Object.values(tableNames)
    });

  } catch (error) {
    console.error('删除设备失败:', error);
    return NextResponse.json(
      { error: '删除设备失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}
